<!DOCTYPE html>
<html lang="zh">

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>
    
    ES6 Promise - DSRBLOG
    
  </title>
  

  
  
  <link href="atom.xml" rel="alternate" title="DSRBLOG" type="application/atom+xml">
  <link rel="stylesheet" href="asset/css/style.min.css">
  <link rel="stylesheet" href="asset/css/doc.css">
  <script src="asset/app.js"></script>


</head>

<body> <section class="ct-body">
	<div class="container">
		<div class="columns is-variable bd-klmn-columns is-4 is-centered">
			<div class="column is-four-fifths">
				<div class="post-body single-content">
					
					<h1 class="title">
						ES6 Promise
					</h1>


					<div class="media">
						
						
						<div class="media-content">
							<div class="content">
								<p>
									<span class="date">2022/09/25 20:06 下午</span>
									

									

									<br />
									<span class="tran-tags">Tags:</span>&nbsp;
									
									<a class="tag is-link is-light">#ES6新特性</a>
									

								</p>
							</div>
						</div>

					</div>
				</div>
				<article class="markdown-body single-content">
					<p><code>Promise</code>是<code>ES6</code>引入的<strong>异步编程</strong>的新解决方案</p>
<p><code>Promise</code>是一个构造函数，用来封装异步操作并可以获取其成功或失败的结果</p>
<h2><a id="%E5%9F%BA%E6%9C%AC%E8%AF%AD%E6%B3%95" class="anchor" aria-hidden="true"><span class="octicon octicon-link"></span></a>基本语法</h2>
<pre class="line-numbers"><code class="language-js">//实例化Promise对象
const p = new Promise(function(resolve,reject){
        setTimeout(() =&gt; {
            let data = '数据库中的用户数据';
            let err = '数据读取失败'
            resolve(data); //成功
            reject(err); //失败
        }, 1000)
    });

//调用Promise对象的then方法
p.then(function(value){ 
    console.log(value); //成功
},function(reason){ 
    console.error(reason);  //失败
})
</code></pre>
<h2><a id="%E8%AF%BB%E5%8F%96%E6%96%87%E4%BB%B6" class="anchor" aria-hidden="true"><span class="octicon octicon-link"></span></a>读取文件</h2>
<pre class="line-numbers"><code class="language-js">//引入fs模块
const fs = require('fs');

//调用方法读取文件
// fs.readFile('./Promise.md', (err, data) =&gt; {
//     if (err) throw err;

//     console.log(data.toString());
// });

//使用Promise封装
const p = new Promise(function(resolve,reject){
    fs.readFile('./Promise.md', (err, data) =&gt; {
        if (err) reject(err);

        resolve(data);
    });
});

p.then(function(value){
    console.log(value.toString());
},function(reason){
    console.log(reason);
})
</code></pre>
<h2><a id="%E5%B0%81%E8%A3%85ajax" class="anchor" aria-hidden="true"><span class="octicon octicon-link"></span></a>封装AJAX</h2>
<h3><a id="%E5%8E%9F%E7%94%9F%E6%96%B9%E6%B3%95" class="anchor" aria-hidden="true"><span class="octicon octicon-link"></span></a>原生方法</h3>
<pre class="line-numbers"><code class="language-js">//创建对象
const xhr = new XMLHttpRequest();

//初始化
xhr.open(&quot;GET&quot;, &quot;https://api.apiopen.top/getJoke&quot;);

//发送
xhr.send();

//绑定事件，处理响应结果
xhr.onreadystatechange = function () {
    //判断
    if (xhr.readyState === 4) {
        //判断响应状态码 200-299 成功
        if (xhr.status &gt;= 200 &amp;&amp; xhr.status &lt; 300){
            //表示成功
            console.log(xhr.response);
        }else{
            console.error(xhr.status);
        }
    }
}
</code></pre>
<h3><a id="promise%E5%B0%81%E8%A3%85" class="anchor" aria-hidden="true"><span class="octicon octicon-link"></span></a>Promise封装</h3>
<pre class="line-numbers"><code class="language-js">const p = new Promise((resolve, reject) =&gt; {
    //创建对象
    const xhr = new XMLHttpRequest();

    //初始化
    xhr.open(&quot;GET&quot;, &quot;https://api.apiopen.top/getJoke&quot;);

    //发送
    xhr.send();

    //绑定事件，处理响应结果
    xhr.onreadystatechange = function () {
        //判断
        if (xhr.readyState === 4) {
            //判断响应状态码 200-299 成功
            if (xhr.status &gt;= 200 &amp;&amp; xhr.status &lt; 300) {
                //表示成功
                resolve(xhr.response);
            } else {
                reject(xhr.status);
            }
        }
    }
})

p.then(function(value){
    console.log(value);
},function(reason){
    console.error(reason);
})
</code></pre>
<h2><a id="promise-prototype" class="anchor" aria-hidden="true"><span class="octicon octicon-link"></span></a>Promise.prototype</h2>
<h3><a id="then%E6%96%B9%E6%B3%95" class="anchor" aria-hidden="true"><span class="octicon octicon-link"></span></a>then()方法</h3>
<p>用于指定回调</p>
<ul>
<li>
<p><code>then()</code>方法的返回结果是Promise对象</p>
</li>
<li>
<p>对象状态由回调函数的执行结果决定</p>
<ol>
<li>
<p>如果回调函数中返回的结果是非<code>Promise</code>类型的数据，状态为成功，返回值为对象的成功值（<strong>函数内若没有<code>return</code>，则默认返回<code>undefined</code>，状态也为成功</strong>）</p>
</li>
<li>
<p>如果回调函数中返回的结果是<code>Promise</code>对象，<code>then()</code>的状态由返回结果决定，返回值是回调函数结果的返回值</p>
</li>
</ol>
</li>
</ul>
<pre class="line-numbers"><code class="language-js">//创建Promise对象
const p = new Promise((resolve, reject) =&gt; {
    setTimeout(()=&gt;{
        resolve('用户数据');
    },1000)
})

//调用then方法
p.then((value)=&gt;{
    console.log(value);
},(reason)=&gt;{
    console.warn(reason);
})
</code></pre>
<h4><a id="%E8%AF%BB%E5%8F%96%E5%A4%9A%E4%B8%AA%E6%96%87%E4%BB%B6" class="anchor" aria-hidden="true"><span class="octicon octicon-link"></span></a>读取多个文件</h4>
<p>对<code>then()</code>方法进行链式调用</p>
<pre class="line-numbers"><code class="language-js">const p = new Promise((resolve, reject) =&gt; {
    fs.readFile('./fs1.md', (err, data) =&gt; {
        resolve(data);
    });
});

p.then(value =&gt; {
    return new Promise((resolve, reject) =&gt; {
        fs.readFile('./fs2.md', (err, data) =&gt; {
            resolve([value,data]);
        });
    })
}).then(value =&gt; {
    fs.readFile('./fs3.md', (err, data) =&gt; {
        value.push(data);
        console.log(value.join('\n'));
    });
})
</code></pre>
<h3><a id="catch%E6%96%B9%E6%B3%95" class="anchor" aria-hidden="true"><span class="octicon octicon-link"></span></a>catch()方法</h3>
<p>用于指定<code>Promise</code>失败的回调</p>
<pre class="line-numbers"><code class="language-js">//创建Promise对象
const p = new Promise((resolve, reject) =&gt; {
    setTimeout(()=&gt;{
        reject('ERROR');
    },1000)
})

//调用catch方法
p.catch(reason=&gt;{
    console.error(reason)
})
</code></pre>

				</article>
				<div class="comments-wrap">
					<div class="share-comments">
						

						

						
					</div>
				</div><!-- end comments wrap -->
			</div>
		</div><!-- end columns -->
	</div><!-- end container -->
</section>  














<script src="asset/prism.js"></script>









</body>

</html>